// web/src/app/(employee)/meet/employee/[id]/page.tsx
'use client';

import React, {useEffect, useState, useRef} from 'react';

import useChat from '@/hooks/useChat';

import {E_WssChannel, T_WssChannel} from '@/lib/ws.types';
import {db} from "@/lib/db";
import {getMeetInfo} from "@/app/(employee)/meet/employee/[id]/actions/getMeetInfo";
import {Employee, Hr} from "@prisma/client";
import {Student} from "@/lib/employee/type";
import ChatInput from "@/app/(employee)/meet/_components/chat-input";
import {map} from "zod";
import {Avatar, AvatarFallback, AvatarImage} from "@/components/ui/avatar";
import {Card, CardContent, CardDescription, CardHeader} from "@/components/ui/card";
import Preview from "@/components/learn/preview";
import {Textarea} from "@/components/ui/textarea";

/// 来源: https://blog.designly.biz/roll-your-own-real-time-chat-server-with-next-js-and-websockets
export default function Page({searchParams, params}: {
    params: {
        id: string
    },
    searchParams: {
        role: string
    }
}) {
    // meet-id为职位id-hr_id-当前用户id, role: user|hr
    // let ids = params.id.split('-')
    let ids = params.id.split('*malred*')
    console.log(ids)
    console.log(searchParams)

    const [employee, setEmployee] = useState<Employee>()
    const [student, setStudent] = useState<Student>()
    const [hr, setHr] = useState<Hr>()
    useEffect(() => {
        (async () => {
            const {s, h, e} =
                await getMeetInfo({
                    eid: ids[0],
                    hid: ids[1],
                    uid: ids[2],
                })
            // @ts-ignore
            setStudent(s!)
            setHr(h!)
            setEmployee(e!)

            // 非学生账号进入该页面无法找到学生信息, 会导致报错
            console.log(s, h, e)
            if (searchParams.role && searchParams.role === 'user') setHandle(s?.name!)
            // @ts-ignore
            else setHandle(h.user.name)
            // @ts-ignore
            setChannel(params.id);

            handleConnect()
        })()
    }, [params.id])

    const {messages, wsError, connected, sendMessage, connect, disconnect, validateHandle} = useChat();

    const logEndRef = useRef<HTMLPreElement>(null);

    const [channel, setChannel]
        // @ts-ignore
        = useState<T_WssChannel>(`${params.id}`);
    // 发送者名称
    const [handle, setHandle] = useState<string>('');
    const [errors, setErrors] = useState<any>({});
    const [messageInput, setMessageInput] = useState<string>('');

    useEffect(() => {
        setErrors((prev: any) => ({...prev, connect: wsError}));
    }, [wsError]);

    // Effect to scroll to the bottom of the log
    useEffect(() => {
        if (logEndRef.current) {
            logEndRef.current.scrollTop = logEndRef.current.scrollHeight;
        }
    }, [messages]);

    const handleChange = (e: React.ChangeEvent<HTMLSelectElement | HTMLInputElement>) => {
        setErrors({});

        const name = e.target.name;
        const value = e.target.value;

        if (name === 'channel') {
            setChannel(value as T_WssChannel);
        } else if (name === 'handle') {
            // Format handle and uppercase first letter
            const modifiedHandle = value
                .replace(/[^a-zA-Z0-9_]/g, '')
                .toLowerCase()
                .replace(/^[a-z]/, c => c.toUpperCase());
            setHandle(modifiedHandle);
        }
    };

    const handleConnect = () => {
        setErrors({});

        console.log(handle)
        // Validate handle
        // if (!validateHandle(handle)) {
        //     setErrors({
        //         handle: 'Handle must be 3-16 characters long and contain only letters, numbers, and underscores',
        //     });
        //     return;
        // }

        console.log(handle, channel)

        // Validate channel
        // const channels = Object.keys(E_WssChannel);
        // if (!channels.includes(channel)) {
        //     setErrors({channel: 'Invalid channel'});
        //     return;
        // }

        try {
            connect({channel, handle});
        } catch (err: any) {
            setErrors({connect: err.message});
        }
    };

    const handleSendMessage = () => {
        setErrors({});

        if (!messageInput) {
            setErrors({message: 'Message cannot be empty'});
            return;
        }

        try {
            sendMessage(messageInput);
            setMessageInput('');
        } catch (err: any) {
            setErrors({message: err.message});
        }
    };

    return (
        <div className="w-full justify-center mt-12 max-w-5xl flex flex-col gap-6 mx-auto border-2 rounded-xl p-6">
            <div className="grid grid-cols-2 gap-4">
            </div>
            <div className="bg-sky-300 p-2 rounded-md fixed inset-y-36 inset-x-64 flex
            items-center gap-6 z-50 justify-center w-fullx w-24 h-8">
                {connected ? (
                    <button className="btn btn-secondary" onClick={disconnect}>
                        Disconnect
                    </button>
                ) : (
                    <button className="btn btn-primary" onClick={handleConnect}>
                        Connect
                    </button>
                )}
            </div>
            <div className="w-full text-center text-sm text-error">{errors.connect || ' '}</div>

            {messages.length === 0 ? (
                <div>还没有消息</div>
            ) : (
                <div className={`flex flex-col gap-y-4`}>
                    {messages.map((message, idx) => {
                            // @ts-ignore
                            if (message.includes(`${hr?.user.name}`)) {
                                return <Card className={`max-w-[60%] shadow-md
                ${searchParams.role === 'hr' ? 'ml-auto w-[60%]' : ''}`} key={idx}>
                                    <CardHeader className={`gap-x-2 items-center
                                    ${searchParams.role === 'hr' ? 'flex-row-reverse' : 'flex-row'}`}>
                                        <Avatar
                                            // @ts-ignore
                                            title={hr?.user.name}
                                            className={`size-11 mr-2 rounded-full`}>
                                            <AvatarImage className={`rounded-full`}
                                                // @ts-ignore
                                                         src={hr.user?.image}/>
                                            <AvatarFallback className={`bg-blue-400 text-white rounded-full`}>
                                                {/*@ts-ignore*/}
                                                {hr.user.name.charAt(0).toUpperCase()}
                                            </AvatarFallback>
                                        </Avatar>
                                        {/*<span>{hr.user.name}</span>*/}
                                        <Preview className={`text-lg 
                ${searchParams.role === 'hr' ? 'mr-auto' : ''}`} value={message.slice(
                                            message.lastIndexOf(':') + 2
                                        )}/>
                                    </CardHeader>
                                </Card>
                            }

                            // 当前role为user, 消息在右边, 否则在左边
                            // ml-auto自动margin左边, 把内容顶到右边
                            return <Card key={idx}
                                         className={
                                             `max-w-[60%] shadow-md
                ${searchParams.role === 'user' ? 'ml-auto w-[60%]' : ''}`
                                         }>
                                <CardHeader className={`gap-x-2 items-center
                ${searchParams.role === 'user' ? 'flex-row-reverse' : 'flex-row'}`}>
                                    <Avatar
                                        // @ts-ignore
                                        title={student?.user.name}
                                        className={`size-11 mr-2 rounded-full`}>
                                        <AvatarImage className={`rounded-full`}
                                            // @ts-ignore
                                                     src={student.user?.image}/>
                                        <AvatarFallback className={`bg-blue-400 text-white rounded-full`}>
                                            {/*@ts-ignore*/}
                                            {student.user.name.charAt(0).toUpperCase()}
                                        </AvatarFallback>
                                    </Avatar>
                                    {/*<span>{student.user.name}</span>*/}

                                    <Preview className={`text-lg 
                ${searchParams.role === 'user' ? 'mr-auto' : ''}`} value={message.slice(
                                        message.lastIndexOf(':') + 2
                                    )}/>
                                </CardHeader>
                            </Card>
                        }
                    )}
                </div>
            )}
            <div className="form-control">
                <Textarea
                    className="textarea textarea-bordered w-full"
                    value={messageInput}
                    placeholder={`和${searchParams.role === 'user' ? 'hr' : '求职者'}沟通 (按enter键发送)`}
                    onChange={e => setMessageInput(e.target.value)}
                    onKeyDown={e => {
                        if (e.key === 'Enter' && !e.shiftKey) {
                            e.preventDefault();
                            handleSendMessage();
                        }
                    }}
                />
                <label className="label">
                    <span className="label-text-alt text-error">{errors.message || ' '}</span>
                </label>
            </div>
        </div>
    );
}
